package com.by.service.impl;

import com.by.bean.CPXJ;
import com.by.bean.SWXJ;
import com.by.bean.TGXJ;
import com.by.controller.MapperFactory;
import com.by.mapper.*;
import com.by.service.QuoteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

@Service
public class QuoteServiceImpl<T> implements QuoteService<T> {

    private final QuoteMapper quoteMapper;
    private final MapperFactory mapperFactory;

    @Autowired
    public QuoteServiceImpl(QuoteMapper quoteMapper, MapperFactory mapperFactory) {
        this.quoteMapper = quoteMapper;
        this.mapperFactory = mapperFactory;
    }

    @Override
    public int save(T entity, String entityType, int id) {
        // 获取报价编码
        String quoteCode = generateQuoteCode(id);

        if (entity instanceof CPXJ) {
            ((CPXJ) entity).setQuoteCode(quoteCode); // 假设CPXJ有一个setQuoteCode方法
        } else if (entity instanceof SWXJ) {
            ((SWXJ) entity).setQuoteCode(quoteCode); // 假设SWXJ有一个setQuoteCode方法
        } else if (entity instanceof TGXJ) {
            ((TGXJ) entity).setQuoteCode(quoteCode); // 假设TGXJ有一个setQuoteCode方法
        }

        // 根据实体类型获取对应的Mapper
        SpecificMapper<T> specificMapper = mapperFactory.getMapper(entityType);
        if (specificMapper == null) {
            throw new IllegalArgumentException("Unsupported entity type: " + entityType);
        }
        return specificMapper.save(entity);
    }

    @Override
    public String generateQuoteCode(int id) {
        // 获取询价编码
        String inquiryCode = quoteMapper.queryInquiryCode(id);
        // 查询最大报价编码
        String maxCode = quoteMapper.queryMaxCode(id);

        if (maxCode == null) {
            // 如果没有找到任何报价，生成初始报价编码
            return inquiryCode + "01";
        } else {
            // 存在报价，根据现有最大编号生成新的报价编码
            String prefix = maxCode.substring(0, maxCode.length() - 2);
            int num = Integer.parseInt(maxCode.substring(maxCode.length() - 2));
            return prefix + String.format("%02d", num + 1);
        }
    }
}
